package cn.webrx.bs.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-08-06 11:20
 */
@WebFilter("/admin/*")
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain c) throws IOException, ServletException {
        /* 检查登录没有，检查是不是登录面 验证码 */
        HttpServletRequest req = (HttpServletRequest)request;
        HttpSession session = req.getSession();
        String uri = req.getRequestURI();
        boolean flag = false;
        if("/admin/login".equals(uri) || "/admin/captcha".equals(uri) || "action=login".equals(req.getQueryString())){
            flag = true;
        }else if(session.getAttribute("admin") != null){
            flag = true;
        }
        HttpServletResponse resp = (HttpServletResponse) response;
        if(flag){
            c.doFilter(request,response);
        }else{
            resp.sendRedirect("/admin/login");
        }
    }

    @Override
    public void init(FilterConfig c) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
